package com.javaweb.common.utils;

import com.javaweb.common.config.UploadFileConfig;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SQLUtils {
    private static Connection conn = null;
    private static SQLUtils instance;


    private SQLUtils() {
    }

    static {
        instance = new SQLUtils();

    }

    public static Connection getConnection() throws Exception {
        Class.forName(UploadFileConfig.driver);
        Connection connection = DriverManager.getConnection(UploadFileConfig.url, UploadFileConfig.username, UploadFileConfig.password);
        return connection;
    }
    public static void SetConnection(Connection connection) {
        //conn = connection;
    }

    //执行sql查询
    public static  void ExecNonQuery(String sql) throws SQLException {
        try {
            conn = getConnection();
            Statement statement = conn.createStatement();
            statement.closeOnCompletion();
            statement.execute(sql);
        } catch(SQLException ex)
        {
            throw ex;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static ResultSet GetResultSet(String sql) throws SQLException {
        ResultSet rs=null;
        try {
            conn = getConnection();
            Statement statement = conn.createStatement();
            statement.closeOnCompletion();
            rs =statement.executeQuery(sql);
        } catch(SQLException ex){
            throw ex;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }


    public static List convertList(ResultSet rs) throws SQLException {
        List list = new ArrayList();
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount(); //Map rowData;
        while (rs.next()) { //rowData = new HashMap(columnCount);
            Map rowData = new HashMap();
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnName(i), rs.getObject(i));
            }
            list.add(rowData);
        }
        return list;
    }
}
